<?php

namespace App\Http\Controllers;

use DB;
use Illuminate\Http\Request;
use Validator;

use Ptime3\Functions\JoinData;

class MailController extends Controller
{

     private function indexInner($input){
        $userId       = $input["user_id"];
        $mailedUserId = $input["mailed_user_id"];
        if(isset($input["set_id"]))
            $setId  = $input["set_id"];
        else
            $setId  = $userId<$mailedUserId?md5($userId."-".$mailedUserId):md5($mailedUserId."-".$userId);

        $baseId = empty($input["base_id"])?0:$input["base_id"];
        $isFresh= isset($input["is_fresh"])?$input["is_fresh"]:0;

        $blackResult = DB::table("ml_black")
            ->where("user_id",$userId)
            ->where("blacked_user_id",$mailedUserId)
            ->first();
        if(!empty($blackResult))
            return $this::jsonResponse(true,"blacking","您已屏蔽此用户");

        DB::beginTransaction();
        $mailResult = DB::table("ml_mail_user")
          ->select("ml_mail_user.id","ml_mail.content","ml_mail.created_at",
               "ml_mail.user_id","ml_mail.mailed_user_id"
               )
          ->leftJoin("ml_mail","ml_mail.id","=","ml_mail_user.mail_id")
          ->where('ml_mail_user.user_id', $userId)
          ->where('ml_mail_user.set_id', $setId)
          ->where('ml_mail_user.is_deleted', false)
          ->where("ml_mail_user.id",($baseId==0 || $isFresh)?">":"<",$baseId)
          ->orderBy("ml_mail.created_at", "DESC")
          ->orderBy("ml_mail_user.id", "DESC");

        if($isFresh)
            $mailResult = $mailResult->get();
        else
            $mailResult = $mailResult->take(20)->skip(0)->get();
        
        DB::table("ml_mail_user")
            ->where("user_id",$userId)
            ->where("set_id",$setId)
            ->where("is_viewed",false)
            ->where("is_deleted",false)
            ->update(["is_viewed"=>true]);
        DB::commit();

        $mailResult = JoinData::user($mailResult);
        $mailResult = JoinData::user($mailResult,"mailed_user");

        return $this::jsonResponse(false,$mailResult);
     }

     /**
     * @api {get} /mail GetMailList
     * @apiVersion 0.2.0
     * @apiName GetMailList
     * @apiGroup mail
     * @apiPermission app
     *
     * @apiDescription 获取私信列表
     *
     * @apiParam {Number} user_id *用户id.
     * @apiParam {Number} mailed_user_id *被私信用户id.
     * @apiParam {Number} set_id 私信集id.
     * @apiParam {Number} base_id 基准私信id.
     * @apiParam {Boolean} is_fresh 是否为更新.
     *
     * @apiSuccess {Boolean} error 是否错误.
     * @apiSuccess {Object[]} result 私信数据.
     * @apiSuccess {String} result.content 私信内容.
     * @apiSuccess {Datetime} result.created_at 创建时间.
     * @apiSuccess {String} result.user_id 用户id.
     * @apiSuccess {String} result.user_name 用户姓名.
     * @apiSuccess {String} result.user_icon 用户头像.
     * @apiSuccess {String} result.mailed_user_id 被私信者id.
     * @apiSuccess {String} result.mailed_user_name 被私信者姓名.
     * @apiSuccess {String} result.mailed_user_icon 被私信者头像.
     * @apiSuccess {String} message 提示消息
     *
     * @apiError statusError 状态错误.
     * @apiSampleRequest http://dev.timepicker.cn/api/mail
     */
	function index(Request $request){
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'user_id' => 'required|integer|min:1',
                'mailed_user_id' => 'required|integer|min:1',
                'set_id'  => 'string|min:32',
                'base_id' => 'integer',
                'is_fresh'=> 'boolean'
            ]
        );
        if($validator->fails())
            return $this::jsonResponse(true,$validator->messages(),"paramError");

        return $this->indexInner($input);
    }

    /**
     * @api {post} /mail CreateMail
     * @apiVersion 0.2.0
     * @apiName CreateMail
     * @apiGroup mail
     * @apiPermission app
     *
     * @apiDescription 创建私信
     *
     * @apiParam {Number} user_id *用户id.
     * @apiParam {Number} mailed_user_id *被私信用户id.
     * @apiParam {String} content *内容.
     * @apiParam {Number} base_id 基准私信id.
     *
     * @apiSuccess {Boolean} error 是否错误.
     * @apiSuccess {Number} result 新建私信id.
     * @apiSuccess {String} message 提示消息.
     *
     * @apiError paramError 参数错误.
     * @apiSampleRequest http://192.168.1.120:82/api/mail
     */
     public function store(Request $request){
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'user_id'        => 'required|integer|min:1',
                'mailed_user_id' => 'required|integer|min:1',
                'content'        => 'required|string|min:2',
                'base_id'        => 'integer',
            ]
        );
        if($validator->fails()){
            return $this::jsonResponse(true,$validator->messages(),"paramError");
        }

        $userId       = $input["user_id"];
        $mailedUserId = $input["mailed_user_id"];

        //黑名单检验
        $blackResult = DB::table("ml_black")
            ->where("user_id",$mailedUserId)
            ->where("blacked_user_id",$userId)
            ->first();
        if(!empty($blackResult))
            return $this::jsonResponse(true,false,"由于对方设置无法发送此私信");

        if($userId == $mailedUserId)
            return $this::jsonResponse(true,false,"不能给自己发私信");

        //添加
        $setId = $userId<$mailedUserId?md5($userId."-".$mailedUserId):md5($mailedUserId."-".$userId);

        DB::beginTransaction();
        DB::table("ml_mail_user")
          ->where('set_id', $setId)
          ->where('is_latested', true)
          ->update(["is_latested"=>false]);

        
        $mailData = [
            "user_id"        => $userId,
            "mailed_user_id" => $mailedUserId,
            "set_id"         => $setId,
            "content"        => $input["content"]
        ];
        $mailId = DB::table("ml_mail")->insertGetId($mailData);

        $mailUserData = [
            [
                "user_id" => $userId,
                "mail_id" => $mailId,
                "set_id"  => $setId,
                "is_viewed"=> true
            ],
            [
                "user_id" => $mailedUserId,
                "mail_id" => $mailId,
                "set_id"  => $setId,
                "is_viewed"=> false
            ]
        ];
        DB::table("ml_mail_user")->insert($mailUserData);
        DB::commit();

        $baseId = empty($input["base_id"])?0:$input["base_id"];
        $mailData = [
            "user_id"         =>$userId,
            "mailed_user_id"  =>$mailedUserId,
            "set_id"          =>$setId,
            "base_id"         =>$baseId,
            "is_fresh"        =>true
        ];
        return $this->indexInner($mailData);
     }


    /**
     * @api {delete} /mail/{id} DeleteMail
     * @apiVersion 0.2.0
     * @apiName DeleteMail
     * @apiGroup mail
     * @apiPermission app
     *
     * @apiDescription 删除私信
     *
     * @apiParam {Number} user_id *用户id.
     *
     * @apiSuccess {Boolean} error 是否错误.
     * @apiSuccess {Boolean} result 结果.
     * @apiSuccess {String} message 提示消息.
     *
     * @apiError paramError 参数错误.
     * @apiSampleRequest http://192.168.1.120:82/api/mail/1
     */
     public function destroy(Request $request, $mailId){
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'user_id'        => 'required|integer|min:1'
            ]
        );
        if($validator->fails())
            return $this::jsonResponse(true,$validator->messages(),"paramError");
        
        $userId = $input["user_id"];

        DB::beginTransaction();
        $result = DB::table("ml_mail_user")
            ->where("user_id",$userId)
            ->where("id",$mailId)
            ->update(["is_deleted"=>true,"is_latested"=>false]);

        $setId = DB::table("ml_mail_user")->where("id",$mailId)->pluck("set_id");
        $latestMailUser = DB::table("ml_mail_user")
            ->select("id")
            ->where("user_id",$userId)
            ->where("set_id",$setId)
            ->where("is_deleted",false)
            ->orderBy("id","DESC")
            ->first();
        if(!empty($latestMailUser))
            DB::table("ml_mail_user")->where("id",$latestMailUser->id)->update(["is_latested"=>true]);
        DB::commit();

        return $this->jsonResponse(false,$result);
     }

     function isNew(Request $request){
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'user_id' => 'required|integer'
            ]
        );
        if($validator->fails())
            return $this::jsonResponse(true,$validator->messages(),"paramError");

        $userId = $input["user_id"];

        $mailUserResult = DB::table("ml_mail_user")
          ->select("id")
          ->where('user_id', $userId)
          ->where('is_viewed', false)
          ->where('is_deleted', false)
          ->first();

        return $this->jsonResponse(false,!empty($mailUserResult));
     }

     /**
     * @api {get} /mail/set GetMailSetList
     * @apiVersion 0.2.0
     * @apiName GetMailSetList
     * @apiGroup mail
     * @apiPermission app
     *
     * @apiDescription 私信集列表
     *
     * @apiParam {Number} user_id *当前用户id.
     *
     * @apiSuccess {Boolean} error 是否错误.
     * @apiSuccess {Object[]} result 私信数据.
     * @apiSuccess {String} result.content 私信内容.
     * @apiSuccess {Datetime} result.created_at 创建时间.
     * @apiSuccess {String} result.user_id 用户id.
     * @apiSuccess {String} result.user_name 用户姓名.
     * @apiSuccess {String} result.user_icon 用户头像.
     * @apiSuccess {String} result.mailed_user_id 被私信者id.
     * @apiSuccess {String} result.mailed_user_name 被私信者姓名.
     * @apiSuccess {String} result.mailed_user_icon 被私信者头像.
     * @apiSuccess {String} message 提示消息
     *
     * @apiError statusError 状态错误.
     * @apiSampleRequest http://dev.timepicker.cn/api/mail/set
     */
     function setIndex(Request $request){
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'user_id' => 'required|integer'
            ]
        );
        if($validator->fails()){
            return $this::jsonResponse(true,$validator->messages(),"paramError");
        }
        $userId = $input["user_id"];

        $mailSetResult = DB::table("ml_mail_user")
          ->select("ml_mail.content","ml_mail.created_at",
               "ml_mail_user.id","ml_mail_user.is_viewed","ml_mail_user.set_id",
               "ml_mail.user_id","ml_mail.mailed_user_id"
               )
          ->leftJoin("ml_mail","ml_mail.id","=","ml_mail_user.mail_id")
          ->where('ml_mail_user.user_id', $userId)
          ->where('ml_mail_user.is_latested', true)
          ->where('ml_mail_user.is_deleted', false)
          ->orderBy("ml_mail.created_at","DESC")
          ->get();

        foreach ($mailSetResult as $key => $value) {
            if($userId == $value->user_id){
                $value->is_mailer = 1;
                $value->mailed_user_id  = $value->mailed_user_id;
            }else{
                $value->is_mailer = 0;
                $value->mailed_user_id  = $value->user_id;
            }
        }

        $mailSetResult = JoinData::user($mailSetResult);
        $mailSetResult = JoinData::user($mailSetResult,"mailed_user");

        return $this->jsonResponse(false,$mailSetResult);
     }

    /**
     * @api {delete} /mail/set DeleteMailSet
     * @apiVersion 0.2.0
     * @apiName DeleteMailSet
     * @apiGroup mail
     * @apiPermission app
     *
     * @apiDescription 删除私信
     *
     * @apiParam {Number} user_id *用户id.
     * @apiParam {Number} set_id *通知集id.
     *
     * @apiSuccess {Boolean} error 是否错误.
     * @apiSuccess {Boolean} result 结果.
     * @apiSuccess {String} message 提示消息.
     *
     * @apiError paramError 参数错误.
     * @apiSampleRequest http://192.168.1.120:82/api/mail/set
     */
     public function setDestroy(Request $request){
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'user_id'        => 'required|integer|min:1',
                'set_id'         => 'required|string|min:32'
            ]
        );
        if($validator->fails()){
            return $this::jsonResponse(true,$validator->messages(),"paramError");
        }

        $userId = $input["user_id"];
        $setId  = $input["set_id"];

        $result = DB::table("ml_mail_user")
            ->where("user_id",$userId)
            ->where("set_id",$setId)
            ->update(["is_deleted"=>true,"is_latested"=>false]);

        return $this->jsonResponse(false,$result);
     }

}